import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:何人亮
 * Date:2024-08-03
 * 15:56
 */
public class Test {
    public static void main(String[] args) {
        MyStack myStack=new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        myStack.push(2);

        System.out.println(myStack.top());
        System.out.println(myStack.pop());
        System.out.println(myStack.top());
    }
}
class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    public MyStack() {
        queue1=new PriorityQueue<>();
        queue2=new PriorityQueue<>();
    }

    public void push(int x) {
        if(!queue1.isEmpty()){
            queue1.add(x);
        }else if(!queue2.isEmpty()){
            queue2.add(x );
        }else{
            queue1.add(x);
        }
    }

    public int pop() {
        if(empty()){
            return -1;
        }
        if (queue1.isEmpty()){
            int size= queue2.size();
            for (int i = 0; i < size-1; i++) {
                int val=queue2.poll();
                queue1.add(val);
            }
            return queue2.poll();
        }
        else {
            int size= queue1.size();
            for (int i = 0; i < size-1; i++) {
                int val = queue1.poll();
                queue2.add(val);
            }
            return queue1.poll();
        }
    }

    public int top() {
        if(empty()){
            return -1;
        }
        if (queue1.isEmpty()){
            int size= queue2.size();
            for (int i = 0; i < size-1; i++) {
                int val=queue2.poll();
                queue1.add(val);
            }
            int val2= queue2.peek();
            queue1.add(queue2.poll());
            return val2;
        }
        else {
            int size= queue1.size();
            for (int i = 0; i < size-1; i++) {
                int val = queue1.poll();
                queue2.add(val);
            }
            int val2= queue1.peek();
            queue2.add(queue1.poll());
            return val2;
        }
    }

    public boolean empty() {
        return (queue2.isEmpty()&&queue1.isEmpty());
    }
}
